package com.flyme.module.base.provider.controller;


import com.egzosn.pay.common.bean.MethodType;
import com.egzosn.pay.common.bean.PayOrder;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.utils.ApiAssert;
import com.flyme.common.core.utils.JsonUtils;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.entity.SysHtml;
import com.flyme.module.base.client.entity.SysMessage;
import com.flyme.module.base.client.entity.SysMessageSend;
import com.flyme.module.base.client.entity.SysUser;
import com.flyme.module.base.provider.rong.methods.User;
import com.flyme.module.base.provider.service.*;
import com.flyme.module.file.client.entity.SysOffCourse;
import com.flyme.module.file.provider.service.SysOffCourseService;
import com.flyme.module.order.client.entity.Order;
import com.flyme.module.order.client.vo.PayType;
import com.flyme.module.order.provider.service.OrderService;
import com.flyme.module.order.provider.service.PayAccountService;
import com.flyme.module.order.provider.service.PayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * h5
 */
@Controller
@RequestMapping("/common")
public class IndexController {
    @Autowired
    private SysHtmlService htmlService;
    @Autowired
    private SysMessageService messageService;
    @Autowired
    private SysMessageSendService messageSendService;
    @Autowired
    private PayAccountService service;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SysOffCourseService offCourseService;
    @Autowired
    private SysUsercertificateService sysUsercertificateService;
    @Autowired
    private SysUserService userService;

    @GetMapping("/index")
    public String index(ModelMap map, String type) {
        ApiAssert.notNull("参数不能为空", type);
        SysHtml html = htmlService.findByHtmlKey(type);
        map.addAttribute("html", html);
        return "index";
    }
    /**
     * 学习证明
     *
     * @param
     * @return
     */
    @RequestMapping("/downCertifite")
    public String downCertifite(ModelMap map, String userCertifiId) {
        PagerInfo info=new PagerInfo();
        CriteriaQuery<EntityMap> qw = new CriteriaQuery(info);
        qw.select("certificate.certificateName,u.validity,u.awardTime,u.certificateNum,u.userId,u.idCard");
        qw.eq("u.id", userCertifiId);
        qw.createAlias("certificate", "certificate");
        List<EntityMap> userctList = sysUsercertificateService.pageList(qw).getRows();
        EntityMap usercertifite = userctList.get(0);
        SysUser user = null;
        if(ObjectUtils.isNotEmpty(usercertifite.get("idCard"))){
            user = userService.findByIdCard(usercertifite.get("idCard").toString());
        }
        if(ObjectUtils.isNotEmpty(usercertifite.get("userId"))){
            user = userService.getById(usercertifite.get("userId"));
        }
        if(ObjectUtils.isNotEmpty(user)){
            usercertifite.put("userName", user.getUserName());
            usercertifite.put("idCard", user.getIdCard());
            usercertifite.put("avatar", user.getAvatar());
            usercertifite.put("positionName", user.getPositionName());
        }
        map.addAttribute("usercertifite", usercertifite);
        return "zs";
    }

    /**
     * 获取服务协议
     */
    @GetMapping(value = "/getHtml")
    public String getHtml(ModelMap map, String type, String title) {
        ApiAssert.notNull("参数不能为空", type);
        SysHtml html = htmlService.findByHtmlKey(type);
        if (ObjectUtils.isEmpty(html)) {
            html = new SysHtml();
            html.setHtmlCode(type);
            html.setIsParent(0);
            html.setParentId(1L);
            html.setHtmlStatus(1);
            html.setHtmlContent(title);
            html.setHtmlTitle(title);
            htmlService.save(html);
        }
        map.addAttribute("html", html);
        return "index";
    }

    /**
     * 系统消息详情
     */
    @RequestMapping(value = "/getNotice")
    public String getNotice(ModelMap map, String noticeId) {
        ApiAssert.notNull("参数不能为空", noticeId);
        SysMessageSend sysMessageSend = messageSendService.getById(noticeId);
        SysMessage message = messageService.getById(sysMessageSend.getMessageId());
        EntityMap html = new EntityMap();
        html.put("htmlTitle", message.getMessageTitle());
        html.put("htmlContent", message.getMessageContent());
        map.addAttribute("html", html);
        sysMessageSend.setMessageStatus(1);
        messageSendService.saveOrUpdate(sysMessageSend);
        return "index";
    }


    /**
     * 获取帮助
     */
    @GetMapping(value = "/help/{id}")
    public String help(ModelMap map, @PathVariable Long id) {
        ApiAssert.notNull("参数不能为空", id);
        SysHtml html = htmlService.getById(id);
        map.addAttribute("html", html);
        return "index";
    }

    /**
     * 折线图
     */
    @GetMapping(value = "/line")
    public String line(ModelMap map,Long userId) {
        map.addAttribute("userId", userId);
        return "line";
    }

    /**
     * 分享页面
     */
    @RequestMapping(value = "/sharePage")
    public String shareApp(ModelMap map, String type, String courseId) {
        map.addAttribute("courseId", courseId);
        if (type.equals("1")) {//在线课程

            map.addAttribute("courseId", courseId);
            return "course";
        }
        if (type.equals("5")) {//线下课程
            SysOffCourse offCourse = offCourseService.getById(courseId);
            map.addAttribute("offCourse", offCourse);
            return "offcourse";
        }
        return "download";
    }

    /**
     * 跳到支付页面 针对实时支付,即时付款
     */
    @RequestMapping(value = "toPay")
    public void toPay(HttpServletRequest request, HttpServletResponse response, String transactionType) {
        String payCode = request.getParameter("payCode");
        request.setAttribute("payCode", payCode);
        String orderId = request.getParameter("orderId");
        orderService.editOrder(UUID.randomUUID().toString().replace("-", ""), orderId, payCode);// 更新订单的第三方流水号
        Order order = orderService.getById(orderId);
        BigDecimal price = order.getOrderAmount();        //正式价格
//        BigDecimal price = new BigDecimal("0.05");      //测试价格：统一 0.05
        // 获取对应的支付账户操作工具（可根据账户id）
        PayResponse payResponse = service.getPayResponsePC(request);
        PayOrder payOrder = new PayOrder(order.getOrderTitle(), order.getOrderBody(), null == price ? new BigDecimal(0.01) : price, order.getOutTradeNo() + "", PayType.valueOf(payResponse.getStorage().getPayType()).getTransactionType(transactionType));
        Map<String, Object> orderInfo = payResponse.getService().orderInfo(payOrder);
        String html = payResponse.getService().buildRequest(orderInfo, MethodType.POST);
        JsonUtils.writeToWeb(html, response);
    }

    /**
     * 网站同步回调
     */
    @RequestMapping(value = "payback")
    public String payback(String out_trade_no, BigDecimal total_amount) {
        System.out.println(out_trade_no);
        System.out.println(total_amount);
        Order order = orderService.findByNo(out_trade_no);
        Long orderId = order.getId();
        //return "redirect:http://web.cbstudy.com/#/success?orderId=" + orderId;
        return "redirect:http://test.cbstudy.com/#/success?orderId=" + orderId;
    }


}
